import threading
import time
import tkinter


class Metronome:
    def __init__(self, ms=None, count=None, function=None, stop_callback=None, *args, **kwargs):
        self._count = count
        self._function = function
        self._args = args
        self._kwargs = kwargs
        self._interval = ms / count / 1000.0  # 将间隔时间转换为秒
        self._stop_callback = stop_callback
        self._stop_event = threading.Event()
        self._thread = None

    def _worker(self):
        for _ in range(self._count):
            if self._stop_event.is_set():
                break
            start_time = time.time()
            self._function(*self._args, **self._kwargs)  # 调用传入的函数
            elapsed_time = time.time() - start_time
            time_to_wait = self._interval - elapsed_time
            if time_to_wait > 0:
                self._stop_event.wait(time_to_wait)  # 使用 Event 对象来等待

        # 设置停止事件，但不等待线程结束
        self._stop_event.set()

        # 调用停止回调函数
        if self._stop_callback is not None:
            self._stop_callback()

    def start(self):
        if self._thread is None or not self._thread.is_alive():
            self._stop_event.clear()
            self._thread = threading.Thread(target=self._worker)
            self._thread.start()

    def stop(self):
        self._stop_event.set()
        if self._thread is not None and self._thread.is_alive():
            self._thread.join()


if __name__ == '__main__':
    def your_function():
        window.bell()


    def on_counter_stop():
        window.quit()


    window = tkinter.Tk()
    window.withdraw()

    metronome = Metronome(60000, 150, your_function, on_counter_stop)
    metronome.start()

    window.mainloop()
